var express = require('express');
var router = express.Router();
var ModelUser = require('../model/Users');
var bodyParser = require('body-parser');
let md5 = require('js-md5');
// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false })

/* GET users listing. */
router.get('/', function(req, res, next) {
  // res.send('respond with a resource');
  res.render( "index" );
});

/* GET users listing. */
router.get('/add_user_', function(req, res, next) {
  let user_model  = new ModelUser();
  user_model.add({
    name: 'test_name111',
    password: 'test_password111',
  });
});
router.post('/add_user', urlencodedParser , function(req, res, next) {
  let user_model  = new ModelUser();
  user_model.add({
    name: req.body.name,
    password: md5(req.body.password),
  });
  res.end(JSON.stringify({
    servertime: new Date().getTime() / 1000,
    ok: true,
  }));
});

router.post('/login', urlencodedParser , async function(req, res, next) {
  let user_model  = new ModelUser();
  let post_name = req.body.name;
  let post_password = req.body.password;
  let result = await user_model.search({
    name: post_name,
  });
  let status;
  if(result[0].password === md5(post_password)){
    status = true;
  }else{
    status = false;
  }
  res.end(JSON.stringify({
    servertime: new Date().getTime() / 1000,
    ok: status,
    id: result[0].id,
    name: result[0].name,
  }));
});

router.post('/edit_profile', urlencodedParser , async function(req, res, next) {

  let user_model  = new ModelUser();
  let id = req.body.id;
  let sex = req.body.sex;
  let introduce = req.body.introduce;
  let nikename = req.body.nikename;
  let avatar = req.body.avatar;
  let email = req.body.email;
  let phone = req.body.phone;
  let address = req.body.address;
  let status;
  try{
    let result = await user_model.update({
      id,
      sex,
      introduce,
      nikename,
      avatar,
      email,
      phone,
      address,
      age:18
    });
    res.end(JSON.stringify({
      servertime: new Date().getTime() / 1000,
      ok: true
    }));
  }catch(e){
    res.end(JSON.stringify({
      servertime: new Date().getTime() / 1000,
      ok: false
    }));
  }
});
router.post('/get_profile', urlencodedParser , async function(req, res, next) {

  let user_model  = new ModelUser();
  let id = req.body.id;
  try{
    let result = await user_model.search({
      id,
    });
    res.end(JSON.stringify({
      servertime: new Date().getTime() / 1000,
      ok: true,
      ...result[0]
    }));
  }catch(e){
    res.end(JSON.stringify({
      servertime: new Date().getTime() / 1000,
      ok: false
    }));
  }
});

module.exports = router;
